<?php

namespace App\Http\Controllers\V1\API;

use App\Http\Controllers\V1\API\BaseController;
use App\Models\V1\ApplyMajors;
use App\Models\V1\Major;
use App\Models\V1\NewStudent;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Http\Response;
use Validator;
use Log;


class ApplyMajorsController extends BaseController
{

    /****
     * 根据大类志愿获取学生专业
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMajors(Request $request) {
        // 自定义返回格式
        $result = array(
            'errorCode' => Response::HTTP_NOT_FOUND,
            'errorMsg' => Response::$statusTexts[Response::HTTP_NOT_FOUND],
            'data' => array()
        );
        $error = $this->validateMyApply($request, $result);
        if (!empty($error) || isset($error)) {
            $result = $error;
            return $this->sendResponse($result, $result['errorCode']);
        }
        $code = $request->get('userID');
        $apply = $this->getApplyMajorByCode($code);
        $resultData = array();
        if (empty($apply) || !isset($apply)) {
            $resultData['isSubmit'] = false;
            $majors = $this->getMajorList($code);
            if ($majors->isEmpty()) {
                $result['errorCode'] = Response::HTTP_OK;
                $result['errorMsg'] = Response::$statusTexts[Response::HTTP_NO_CONTENT];
            }else {
                // 格式化数据
                $resultMajors = array();
                foreach ($majors as $item) {
                    $formatMajor = array();
                    $formatMajor['majorCode'] = $item['code'];
                    $formatMajor['majorName'] = $item['name'];
                    array_push($resultMajors, $formatMajor);
                }
                $resultData['majorList'] = $resultMajors;
                $result['errorCode'] = Response::HTTP_OK;
                $result['errorMsg'] = Response::$statusTexts[Response::HTTP_OK];
                $result['data'] = $resultData;
            }
        }else {
            $resultData['isSubmit'] = true;
            // 格式化数据
            $resultMajors = array();
            foreach ($apply as $item) {
                $formatMajor = array();
                $formatMajor['majorCode'] = $item;
                $formatMajor['majorName'] = $this->getMajorNameByCode($item);
                array_push($resultMajors, $formatMajor);
            }
            $resultData['majorList'] = $resultMajors;
            $result['errorCode'] = Response::HTTP_OK;
            $result['errorMsg'] = Response::$statusTexts[Response::HTTP_OK];
            $result['data'] = $resultData;
        }
        return $this->sendResponse($result, $result['errorCode']);
    }



    /****
     * 志愿申请接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function applyMajor(Request $request) {
        $result = array(
            'errorCode' => Response::HTTP_NOT_FOUND,
            'errorMsg' => Response::$statusTexts[Response::HTTP_NOT_FOUND],
        );
        $error = $this->validateApply($request, $result);
        if (!empty($error) || isset($error)) {
            $result = $error;
            return $this->sendResponse($result, $result['errorCode']);
        }
        $wishes = $request->get('wishes');
        if (empty($wishes) || count($wishes) == 0) {
            $result['errorCode'] = Response::HTTP_BAD_REQUEST;
            $result['errorMsg'] = '所选志愿不能为空';
            return $this->sendResponse($result, $result['errorCode']);
        }
        if ($request->method() === 'POST') {
            $rspObj = $this->handleApply($request);
            if ($rspObj) {
                $result['errorCode'] = Response::HTTP_OK;
                $result['errorMsg'] = '志愿申请成功';
            }else{
                $result['errorCode'] = Response::HTTP_BAD_REQUEST;
                $result['errorMsg'] = '志愿申请失败';
            }
        }
        return $this->sendResponse($result, $result['errorCode']);
    }

    /***
     * 验证志愿申请
     * @param Request $request
     */
    private function validateMyApply(Request $request) {
        //校验规则
        $rules = array();
        $rules['userID'] = 'required|exists:basic_new_students,exam_code,deleted_at,NULL|bail';

        //错误提示信息
        $messages = array();
        $messages['userID.required'] = '用户代码不能为空';
        $messages['userID.exists'] = '用户不存在';

        $validator = Validator::make($request->all(),$rules,$messages);  //第一个参数是提交的数据，第二个是校对规则，第三个是错误信息
        $errors = $validator->errors()->all(); //这是捕获到的所有参数验证的错误信息
        if(!empty($errors)) {
            $first_errors = $errors[0];
            $result['errorCode'] = Response::HTTP_BAD_REQUEST;
            $result['errorMsg'] = $first_errors;
            return $result;
        }
    }



    /***
     * 宿舍申请处理
     * @param Request $request
     * @return mixed
     */
    private function handleApply(Request $request) {
        /**
         * 传入的参数
         */
        //申请人
        $userID = $request->get('userID');
        $wishes = $request->get('wishes');
        $majorCodes = collect($wishes)->implode('majorCode',' ');
        $wishIDs = collect($wishes)->implode('wishID',' ');
        $insert_data = [
            'exam_code' => $userID,
            'major_code' => $majorCodes,
            'wish_id' => $wishIDs,
            'arrival_code' => $this->getArrivalCode($userID),
        ];
        $rspObj = ApplyMajors::updateOrCreate(['exam_code'=>$userID],$insert_data);
        /*
        $old_majors = ApplyMajors::where('exam_code',$userID)->get();
        if (!empty($old_majors)){
            foreach ($old_majors as $item) {
                $rspObj = $item->delete();
            }
        }
        foreach ($wishes as $item) {
            $insert_data = [
                'exam_code' => $userID,
                'major_code' => $item['majorCode'],
                'wish_id' => $item['wishID'],
                'arrival_code' => $this->getArrivalCode($userID),
            ];
            $rspObj = ApplyMajors::create($insert_data);
        }
        */
        return $rspObj;
    }



    /***
     * 验证宿舍申请
     * @param Request $request
     */
    private function validateApply(Request $request) {
        //校验规则
        $rules = array();
        $rules['userID'] = 'required|exists:basic_new_students,exam_code,deleted_at,NULL|bail';
        $rules['wishes'] = 'required|bail';

        //错误提示信息
        $messages = array();
        $messages['userID.required'] = '用户代码不能为空';
        $messages['userID.exists'] = '用户不存在';
        $messages['wishes.required'] = '申请专业为空';

        $validator = Validator::make($request->all(),$rules,$messages);  //第一个参数是提交的数据，第二个是校对规则，第三个是错误信息
        $errors = $validator->errors()->all(); //这是捕获到的所有参数验证的错误信息
        if(!empty($errors)) {
            $first_errors = $errors[0];
            $result['errorCode'] = Response::HTTP_BAD_REQUEST;
            $result['errorMsg'] = $first_errors;
            return $result;
        }
    }

    /***
     * 获取校服列表
     * @param $code
     * @return mixed
     */
    private function getMajorList($code){
        $arrival_code = $this->getArrivalCode($code);
        $student = $this->getStudentInfo($code);
        //取出招生目录
        $enrollment_directory = $student['enrollment_directory'];
        $data = Major::where(['parent_code'=>$enrollment_directory,'arrival_code'=>$arrival_code])->get();
        return $data;
    }


    /***
     * 根据考试号获取用户提交的志愿申请
     * @param $code
     * @return mixed
     */
    private function getApplyMajorByCode($code)
    {
        $apply = ApplyMajors::where('exam_code',$code)->first();
        if (!empty($apply) || isset($apply)) {
            $majorCode = $apply['major_code'];
            $wishID = $apply['wish_id'];
            $majorCodes = explode(' ',$majorCode);
            $wishIDs = explode(' ',$wishID);
            //$majorCode会根据wishIDs的排序进行排序
            array_multisort($wishIDs,$majorCodes);
            $apply = $majorCodes;
        }
        return $apply;
    }


    /***
     * 根据考试号获取用户提交的志愿申请
     * @param $code
     * @return mixed
     */
    private function getMajorNameByCode($code)
    {
        $apply = Major::where('code',$code)->first();
        if (empty($apply)) {
            return '';
        }
        return $apply->name;
    }


    /***
     * 根据考试号获取学生基础信息
     * @param $code
     */
    private function getStudentInfo($code){
        $student = NewStudent::where('exam_code',$code)->first();
        return $student;
    }


    /***
     * 获取当前的迎新代码
     * @return array
     */
    private function getArrivalCode($code)
    {
        $student = NewStudent::where('exam_code',$code)->first();
        return $student['arrival_code'];
    }
}
